<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024-03-02 16:58
 * +-------------------------------------------------------------
 */

namespace storage;

use Exception;
use OSS\Http\RequestCore_Exception;
use storage\engine\Alioss;
use storage\engine\Base;
use storage\engine\Local;

class Upload
{
    private array $config;    // upload 配置
    private mixed $engine;    // 当前存储引擎类

    /**
     * 存储引擎类列表
     */
    public const ENGINE_CLASS_LIST = [
        "local"   => Local::class,
        "alioss" => Alioss::class,
    ];

    /**
     * 构造方法
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        //配置文件
        $this->config = $config;
        // 实例化当前存储引擎,如需其他存储，如本地存储，添加其他引擎
        $this->engine = $this->getEngineClass();
    }

    /**
     * 实例化当前存储引擎
     * @return mixed
     */
    private function getEngineClass(): mixed
    {
        $storage = $this->config['storage'] ?? 'local';
        if (!isset(self::ENGINE_CLASS_LIST[$storage])) {
            throw new \RuntimeException("未找到存储引擎类: {$storage}");
        }
        $class  = self::ENGINE_CLASS_LIST[$storage];
        $config = $this->config['engine'] ?? [];
        return new $class($storage, $config);
    }

    /**
     * 设置上传的文件信息
     */
    public function setUploadFile(string $name = '')
    {
        return $this->engine->setUploadFile($name);
    }

    /**
     * 设置上传的文件信息
     * @param string $filePath
     */
    public function setUploadFileByReal(string $filePath)
    {
        return $this->engine->setUploadFileByReal($filePath);
    }

    /**
     * 设置上传文件的验证规则
     * @param array $rules
     */
    public function setValidationScene(array $rules = [])
    {
        return $this->engine->setValidationScene($rules);
    }

    /**
     * 执行文件上传
     */
    public function upload(): bool
    {
        return $this->engine->upload();
    }

    /**
     * 执行文件删除
     * @param string $filePath
     * @return bool
     * @throws RequestCore_Exception
     */
    public function delete(string $filePath): bool
    {
        return $this->engine->delete($filePath);
    }

    /**
     * 获取错误信息
     * @return mixed|string
     */
    public function getError(): mixed
    {
        return $this->engine->getError();
    }

    /**
     * 返回保存的文件信息
     * @return array
     */
    public function getSaveFileInfo(): array
    {
        return $this->engine->getSaveFileInfo();
    }

}